package github.ziwukun.jsonql.orm;

import java.util.LinkedList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonAlias;

import lombok.Data;

/**
 * 链接容器
 * @author Hugo.Yu
 */
@Data
class JoinPropCtnBuilder {
	// 容器名称
	@JsonAlias({"container","ctn","ctnName"})
	String ctnName;
	// 容器类型
	@JsonAlias({"type","ctnType"})
	ContainerType ctnType;
	// 容器的属性和字段定义
	@JsonAlias({"container-props","ctn-props","ctnProps"})
	List<CtnPropBuilder> ctnProps = new LinkedList<>();
	// 链接两个容器的字段名称 外键名
	@JsonAlias({"join-field","joinField"})
	String joinField;
	// 持有外键的*容器*的名称
	@JsonAlias({"mapped-by","mappedBy"})
	String mappedBy;
	
	JoinPropCtnImpl toJoinPropCtn(Container outCtn) {
		return new JoinPropCtnImpl(this,outCtn);
	}
	
	public static void instanceCtn(JoinPropCtnBuilder joinCtnBuilder,JoinPropCtnImpl ctn,
		Container outCtn) {
		OrmAssert.notBlank(joinCtnBuilder.ctnName, "容器名称不能为空");
		OrmAssert.notBlank(joinCtnBuilder.ctnType, "容器类型不能为空");
		OrmAssert.notBlank(joinCtnBuilder.ctnType, "mappedBy不能为空");
		
		ctn.ctnName = joinCtnBuilder.ctnName;
		ctn.ctnType = joinCtnBuilder.ctnType;
		for (CtnPropBuilder ctnProp : joinCtnBuilder.ctnProps) {
			CtnFieldImpl field = ctnProp.toCtnField();
			ctn.fields.add(field);
		}
		
		// 外部容器持有链接字段
		if(joinCtnBuilder.mappedBy.equals(outCtn.ctnName())) {
			ctn.mappedBy = outCtn;
			ctn.joinField = outCtn.getFieldByName(joinCtnBuilder.joinField);
		}
		else if(joinCtnBuilder.mappedBy.equals(ctn.ctnName())){
			ctn.mappedBy = ctn;
			ctn.joinField = ctn.getFieldByName(joinCtnBuilder.joinField);
		}
		else {
			throw new OrmException("错误的mappedBy={}",joinCtnBuilder.mappedBy);
		}
		OrmAssert.notBlank(ctn.joinField, "错误的joinField={}",joinCtnBuilder.joinField);
	}
}
